package com.trex.modules.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.ArrayNode;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JsonGenerator {

    public static String createJson(Map<String, Object> sysInfo, String tableName, List<Map<String, String>> columns, List<List<Object>> rows) throws Exception {
        ObjectMapper mapper = new ObjectMapper();

        // 创建根节点
        ObjectNode root = mapper.createObjectNode();

        // 构建 SysInfo 节点
        ObjectNode sysInfoNode = mapper.createObjectNode();
        sysInfo.forEach((key, value) -> sysInfoNode.put(key, value.toString()));
        root.set("SysInfo", sysInfoNode);

        // 构建 Tables 节点
        ArrayNode tablesArray = mapper.createArrayNode();
        ObjectNode tableNode = mapper.createObjectNode();
        tableNode.put("Name", tableName);

        // 构建 Columns 节点
        ArrayNode columnsArray = mapper.createArrayNode();
        for (Map<String, String> column : columns) {
            ObjectNode columnNode = mapper.createObjectNode();
            column.forEach(columnNode::put);
            columnsArray.add(columnNode);
        }
        tableNode.set("Columns", columnsArray);

        // 构建 Rows 节点
        ArrayNode rowsArray = mapper.createArrayNode();
        for (List<Object> row : rows) {
            ArrayNode rowArray = mapper.createArrayNode();
            for (Object value : row) {
                if (value instanceof String) {
                    rowArray.add((String) value);
                } else if (value instanceof Integer) {
                    rowArray.add((Integer) value);
                } else if (value instanceof Double) {
                    rowArray.add((Double) value);
                }
                // 可以添加更多类型
            }
            rowsArray.add(rowArray);
        }
        tableNode.set("Rows", rowsArray);

        tablesArray.add(tableNode);
        root.set("Tables", tablesArray);

        // 生成 JSON 字符串
        return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root);
    }

    // 发送 GET 请求，解析返回的 JSON，并提取 I_USER_ID
    public static String sendGetRequestAndExtractUserId() {
        StringBuilder content = new StringBuilder();

        try {
            // 创建 URL 对象并打开 HTTP 连接
            HttpURLConnection connection = (HttpURLConnection) new URL("http://172.16.16.129:5000/service/user_info").openConnection();
            connection.setRequestMethod("GET");

            // 获取响应码
            int responseCode = connection.getResponseCode();

            // 如果返回 401 Unauthorized 就终止操作并返回消息
            if (responseCode == 401) {
                return null;
            }

            // 如果返回 200 OK，读取并返回响应内容
            if (responseCode == 200) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;

                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }
                in.close();

                // 获取响应内容后，解析 JSON 并返回 I_USER_ID
                return getUserIdFromJson(content.toString());
            } else {
                return "Request failed with response code: " + responseCode;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return null;  // 返回错误信息
        }
    }

    // 解析 JSON 并返回 I_USER_ID 的方法
    public static String getUserIdFromJson(String jsonData) {
        ObjectMapper objectMapper = new ObjectMapper();
        String userId = null;
        try {
            // 解析 JSON 字符串
            JsonNode rootNode = objectMapper.readTree(jsonData);
            // 获取 "data" 节点
            JsonNode dataNode = rootNode.path("data");
            // 提取 "I_USER_ID" 的值
            userId = dataNode.path("I_USER_ID").asText();  // 将其转为字符串
        } catch (Exception e) {
            e.printStackTrace();  // 打印错误信息
        }

        return userId != null ? userId : "I_USER_ID not found";  // 返回解析到的 I_USER_ID 值
    }

    public static Map<String, String> decodeJWT(String jwt) {
        Map<String, String> decodedParts = new HashMap<>();

        // 分割 JWT，获取 header 和 payload
        String[] parts = jwt.split("\\.");
        if (parts.length >= 2) {
            // 解码 header 和 payload
            String header = new String(Base64.getUrlDecoder().decode(parts[0]));
            String payload = new String(Base64.getUrlDecoder().decode(parts[1]));

            // 将解码结果放入 Map
            decodedParts.put("header", header);
            decodedParts.put("payload", payload);
        } else {
            // 如果 JWT 格式无效，放入错误信息
            decodedParts.put("error", "Invalid JWT format.");
        }

        return decodedParts;
    }
    // 通用方法，解析 JSON 并返回指定键的值
    public static String getValueFromJson(String jsonData) {
        String key = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/sid";
        ObjectMapper objectMapper = new ObjectMapper();
        String value = null;
        try {
            // 解析 JSON 字符串
            JsonNode rootNode = objectMapper.readTree(jsonData);
            // 根据给定的键获取值
            value = rootNode.path(key).asText();
        } catch (Exception e) {
            e.printStackTrace();  // 打印错误信息
        }

    return value;  // 返回解析到的值

    }
    // 从 HttpServletRequest 中提取 accessToken 并解析其负载
    public static String extractAndDecodeAccessToken(HttpServletRequest request) {
        String cookieHeader = request.getHeader("Cookie");
//        String cookieHeader ="jeesite.session.id=c0325005785d401d9a01ebe18c88ae3c; accessToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9zaWQiOiIzNDMiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoi5p2O5bOwIiwiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS93cy8yMDA4LzA2L2lkZW50aXR5L2NsYWltcy9yb2xlIjoi5YiX5qOA6LCD5bqmIiwiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS93cy8yMDA4LzA2L2lkZW50aXR5L2NsYWltcy9ncm91cHNpZCI6IjQyIiwiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS93cy8yMDA4LzA2L2lkZW50aXR5L2NsYWltcy92ZXJzaW9uIjoiMjAyNDEwMTMxMTI5MjEiLCJleHAiOjE3MjkzOTQ5NjF9.CPvMlkQiSjubewPXW2CiCyVHTEEjkPy53mSsn6BhgTs";
        String accessToken = null;

        if (cookieHeader != null) {
            // 分割各个 Cookie
            String[] cookies = cookieHeader.split("; ");
            for (String cookie : cookies) {
                // 解析单个 Cookie
                String[] parts = cookie.split("=", 2);
                if (parts.length == 2 && "accessToken".equals(parts[0])) {
                    accessToken = parts[1]; // 获取 accessToken 的值
                    break; // 找到后可以跳出循环
                }
            }
        }

        // 如果找到 accessToken，则解析 JWT 并返回负载
        if (accessToken != null) {
            Map<String, String> userIdFromJson = JsonGenerator.decodeJWT(accessToken);
            // 直接返回 payload 部分，假设 payload 是 String 类型
            return JsonGenerator.getValueFromJson(userIdFromJson.get("payload"));
        }

        return null; // 如果未找到 accessToken，返回 null
    }

    public static void main(String[] args) throws Exception {
        // 调用合并后的方法，并接收返回的 I_USER_ID
        String userId = sendGetRequestAndExtractUserId();

        // 输出 I_USER_ID
        System.out.println("I_USER_ID: " + userId);
    }

}


